<template>
  <VTable
    v-if="isRefreshTable"
    ref="tableRef"
    v-bind="tableOptins"
    class="is--line"
    @keyup="handleKeyUp"
  >
    <template #form="{ form }">
      <multi-input
        clearable
        v-model="form.task_no"
        style="width: 200px"
        placeholder="任务单号,批量搜索,一行一个"
      ></multi-input>
      <VGroup>
        <el-select class="selectClass !w-[100px]" v-model="form.personnelRange.type">
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <select-personnel
          v-model="form.personnelRange.value"
          :multiple="true"
          placeholder="请选择"
        ></select-personnel>
      </VGroup>
      <VGroup>
        <el-select
          class="selectClass !w-[100px]"
          v-model="form.dateRange.type"
          collapse-tags
          placeholder="创建时间"
        >
          <el-option
            v-for="item in dateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-date-picker
          v-model="form.dateRange.value"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="defaultTime()"
        />
      </VGroup>
      <el-date-picker
        v-model="form.performance_month"
        type="month"
        value-format="YYYY-MM-DD"
        placeholder="请选择绩效月份"
      />
      <teleport v-if="tabsLoad" to="#routine-task">
        <el-tabs class="w-full" v-model="form.status" @tab-click="handleClick">
          <el-tab-pane
            :label="item.label"
            :name="item.name"
            v-for="(item, index) in tabList"
            :key="index"
          >
            <template #label>
              {{ item.label }}(<span
                :class="form.status == item.name ? 'base-text-color' : 'text-[#999999]'"
                >{{ item.count }}</span
              >)
            </template>
          </el-tab-pane>
        </el-tabs>
      </teleport>
    </template>
    <template #toolbar_btns>
      <div id="routine-task" class="w-full" v-dom-load="() => (tabsLoad = true)"></div>
      <VButton
        auth="/goods/task/picture/add"
        type="primary"
        @click="pictureTaskFun('add')"
        >+ 新增非设计任务</VButton
      >
      <!-- <VButton auth="/goods/task/picture/batchPerson" v-show="[1, 2].includes(activeName) || !activeName"
        @click="handleBatch('batchDistriBution')">批量分配人员</VButton> -->
      <VButton
        auth="/goods/task/picture/sumitAudit"
        v-show="[2, 5, 6].includes(activeName) || !activeName"
        @click="handleBatch('haveReviewed')"
        >提交审核</VButton
      >
      <VButton
        auth="/goods/task/picture/batchAudit"
        v-show="[3].includes(activeName) || !activeName"
        @click="handleBatch('designReview')"
        >设计审核</VButton
      >
      <VButton auth="/goods/task/picture/cancel" @click="handleBatch('cancel')"
        >取消</VButton
      >

      <VButton auth="/goods/task/picture/makeTag" @click="handleBatch('makeTag')"
        >打标签</VButton
      >
      <el-dropdown @command="batchOptionsEvent">
        <el-button>
          批量操作<i
            style="font-size: 10px !important"
            class="dk-iconfont icon-ArrowDown"
        /></el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item
              v-for="(item, index) in batchFilterOptions"
              :key="index"
              :command="item.value"
              >{{ item.label }}</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <div class="ml-auto flex items-center cursor-pointer gap-3">
        <el-button @click="handleCustom">自定义字段</el-button>
        <VButton auth="/goods/task/picture/export" @click="handleExport">
          <i class="dk-iconfont icon-Upload" />非设计任务导出
        </VButton>
      </div>
    </template>
  </VTable>
  <checkRoutineImage ref="checkRoutineImageRef" />
  <pictureDialogConption ref="diaLog" @query="queryForm"></pictureDialogConption>
  <pictureListConption ref="refPictureList" />
  <addRoutineTask ref="refAddTask" @query="queryForm" />
  <VLog ref="logRef" :api="queryLogList" :isSearch="true" />
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  <customFields
    ref="customFieldsRef"
    apiName="routine-task"
    :columns="columns"
    @filter-table="getCustomFieldsList"
  ></customFields>
  <copyDialog v-model="copyVisible" :data="copyData" @close="copyData = []" />
  <LabelModal ref="labelModalRef"></LabelModal>
  <pictureStatistics ref="pictureStatisticsRef"></pictureStatistics>
  <editPerformance ref="editPerformanceRef"></editPerformance>
</template>

<script setup lang="jsx" name="RoutineTask">
import {
  queryLogList,
  getNotDesignList,
  cancelTask,
  notDesignStatistics,
  getCustomFields,
} from "./api";
import { getOptions } from "@/api/index";
import addRoutineTask from "./components/addRoutineTask.vue";
import checkRoutineImage from "./components/checkRoutineImage.vue";
import pictureDialogConption from "./components/pictureDialog.vue";
import pictureListConption from "./components/pictureList.vue";
import VLog from "@/components/VLog/index.vue";
import { ElMessage, ElMessageBox, ElSelect } from "element-plus";
import { nextTick, onMounted, ref, toRefs } from "vue";
import useUserStore from "@/store/modules/user";
import DerivedCenter from "@/components/DerivedCenter";
import customFields from "./components/customFields";
import copyDialog from "./components/copyDialog";
import { useRoute } from "vue-router";
import LabelModal from "../../statement/design-performance/components/LabelModal";
import { batchRoutineOptions, userOptions, dateOptions } from "./data.js";
import pictureStatistics from "./components/pictureStatistics.vue";
import editPerformance from "./components/editPerformance.vue";

let options = reactive(inject("options"));

let route = useRoute();
const store = useUserStore();

let activeName = ref("");
const tableRef = ref();
const logRef = ref();
const diaLog = ref(null);
const refPictureList = ref(null);
const refAddTask = ref(null);
const tabsLoad = ref(false);

const data = reactive({
  typeList: [],
  tabList: [
    {
      label: "全部",
      name: "",
      count: 0,
    },
    {
      label: "待分配人员",
      name: 1,
      count: 0,
    },
    {
      label: "待处理",
      name: 2,
      count: 0,
    },
    {
      label: "待设计审核",
      name: 3,
      count: 0,
    },
    {
      label: "待运营审核",
      name: 4,
      count: 0,
    },
    {
      label: "审核未通过",
      name: 5,
      count: 0,
    },
    {
      label: "已完成",
      name: 6,
      count: 0,
    },
    {
      label: "已取消",
      name: 7,
      count: 0,
    },
  ],
  expandActives: [],
  searchOptions: [],
  batchFilterOptions: [],
  options: {},
  CustomFieldsList: [],
  isRefreshTable: false,
  columns: [
    { type: "checkbox", field: "checkbox", width: 80 },
    {
      title: "任务单号",
      field: "task_no",
      minWidth: 150,
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <div class={["font-size-10px", `taskBgColor${row.status}`]}>
                {row.status_text}
              </div>
              <div class={["font-size-10px", "ml-4", `priorityBgColor${row.priority}`]}>
                {row.priority_text}
              </div>
              <div class="flex">
                <VText
                  type="button"
                  value={row.task_no}
                  copy={true}
                  onClick={() => pictureTaskFun("view", row.id)}
                ></VText>
              </div>
            </div>,
          ];
        },
      },
    },

    {
      title: "任务备注",
      field: "task_remark",
      minWidth: 180,
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <el-tooltip
                class="item"
                effect="dark"
                content={row.task_remark || ""}
                placement="top"
              >
                <div class="overflow-line2 text-[#333333]" style="width: 200px">
                  {row.task_remark}
                </div>
              </el-tooltip>
            </div>,
          ];
        },
      },
    },
    {
      title: "图片查看",
      field: "image_view",
      minWidth: 100,
      slots: {
        default: ({ row, rowIndex }) => {
          return [
            <VButton
              auth="/goods/task/picture/download"
              type="primary"
              link
              onclick={() => checkImageFun(row)}
            >
              点击查看
            </VButton>,
          ];
        },
      },
    },
    {
      title: "审核备注",
      field: "remark",
      minWidth: 220,
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <div class="text-[#666666]">设计审核备注：</div>
              <el-tooltip
                class="item"
                effect="dark"
                content={row.designer_comment || ""}
                placement="top"
              >
                <div class="overflow-line2 text-[#333333]" style="width: 200px">
                  {row.designer_comment}
                </div>
              </el-tooltip>
              <div class="text-[#666666]">运营审核备注：</div>
              <el-tooltip
                class="item"
                effect="dark"
                content={row.operators_comment || ""}
                placement="top"
              >
                <div class="overflow-line2 text-[#333333]" style="width: 200px">
                  {row.operators_comment}
                </div>
              </el-tooltip>
            </div>,
          ];
        },
      },
    },
    {
      title: "图片处理人员",
      field: "designer_user",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["designer_user"])}
              />{" "}
              图片处理人员
            </div>
          );
        },
        default: ({ row }) => {
          return <div>{row.designer_user_text || "--"}</div>;
        },
      },
    },
    {
      title: "摄影人员",
      field: "photography_user",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["photography_user"])}
              />{" "}
              摄影人员
            </div>
          );
        },
        default: ({ row }) => {
          return <div>{row.photography_user_text || "--"}</div>;
        },
      },
    },
    {
      title: "编辑人员",
      field: "edit_user",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["edit_user"])}
              />{" "}
              编辑人员
            </div>
          );
        },
        default: ({ row }) => {
          return <div>{row.edit_user_text || "--"}</div>;
        },
      },
    },
    {
      title: "渲染人员",
      field: "render_user",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["render_user"])}
              />{" "}
              渲染人员
            </div>
          );
        },
        default: ({ row }) => {
          return <div>{row.render_user_text || "--"}</div>;
        },
      },
    },
    {
      title: "协助人员",
      field: "assistance_user",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["assistance_user"])}
              />{" "}
              协助人员
            </div>
          );
        },
        default: ({ row }) => {
          return <div>{row.assistance_user_text || "--"}</div>;
        },
      },
    },
    {
      title: "设计审核人",
      field: "user3",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["designer_reviewer"])}
              />{" "}
              设计审核人
            </div>
          );
        },
        default: ({ row }) => {
          return <div>{row.designer_reviewer_text || "--"}</div>;
        },
      },
    },
    {
      title: "绩效标签查看",
      field: "performance_label",
      minWidth: 120,
      slots: {
        default: ({ row }) => {
          return (
            <div
              class="base-text-color cursor-pointer"
              onClick={() => handlePerformanceLabel(row.id)}
            >
              点击查看
            </div>
          );
        },
      },
    },
    {
      title: "创建人",
      field: "create_user",
      minWidth: 160,
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              <svg-icon
                icon-class="tongji"
                class="base-text-color mr-1"
                onclick={() => handleStatistics(["create_user"])}
              />
              创建人
            </div>
          );
        },
        default: ({ row }) => {
          return <div>{row.create_user_text || "--"}</div>;
        },
      },
    },
    {
      title: "创建时间",
      field: "create_time",
      sortable: true,
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return <div>{row.create_time || "--"}</div>;
        },
      },
    },
    {
      title: "提交审核时间",
      field: "review_time",
      sortable: true,
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return <div>{row.review_time || "--"}</div>;
        },
      },
    },
    {
      title: "设计审核时间",
      field: "designer_time",
      sortable: true,
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return <div>{row.designer_time || "--"}</div>;
        },
      },
    },
    {
      title: "更新时间",
      field: "update_time",
      sortable: true,
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return <div>{row.update_time || "--"}</div>;
        },
      },
    },
    {
      title: "绩效月份",
      field: "performance_month",
      sortable: true,
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return <div>{row.performance_month || "--"}</div>;
        },
      },
    },
    {
      title: "是否超额任务",
      field: "is_excess_task",
      minWidth: 110,
      slots: {
        // header: ({ row }) => {
        //   return <span class="flex items-center"><svg-icon icon-class="tongji" class="base-text-color mr-1" onclick={() => handleStatistics(['is_excess_task'])}/>是否超额任务</span>
        // },
        default: ({ row }) => {
          return <div>{row.is_exceed_task_text || "--"}</div>;
        },
      },
    },
    {
      title: "操作",
      field: "operation",
      width: 170,
      fixed: "right",
      slots: {
        default: ({ row, rowIndex }) => {
          // 1 待分配 2 待处理 3待设计审核 4待运营审核 5 审核未通过 6已完成 7已取消
          const showRule = {
            edit: [1, 2, 3, 4, 5], // 编辑
            cancel: [1, 2, 5], // 取消
          };
          return [
            <div>
              <div>
                {showRule["edit"].includes(row.status) && (
                  <VButton
                    auth="/goods/task/picture/edit"
                    link
                    type="primary"
                    onClick={() => pictureTaskFun("edit", row.id)}
                  >
                    编辑
                  </VButton>
                )}
                {showRule["cancel"].includes(row.status) && (
                  <VButton
                    auth="/goods/task/picture/cancel"
                    link
                    type="danger"
                    onclick={() => handleCancelTask(row.id)}
                  >
                    取消
                  </VButton>
                )}
                {/* <VButton auth="/goods/task/picture/edit-performance" type="primary" link onClick={() => handlePerformance(row.id)}>绩效编辑</VButton> */}
                <el-button link type="primary" onClick={() => logRef?.value.open(row.id)}>
                  日志
                </el-button>
              </div>
            </div>,
          ];
        },
      },
    },
  ],
});
const {
  tabList,
  expandActives,
  batchFilterOptions,
  CustomFieldsList,
  isRefreshTable,
  columns,
} = toRefs(data);

// 列表配置
const tableOptins = reactive({
  rowConfig: { height: 60 },
  showOverflow: false,
  showHeaderOverflow: false,
  scrollY: { enabled: false },
  formConfig: {
    save: "routine-task",
    data: {
      productName: { type: "sku", value: "" },
      dateRange: { type: "create_time", value: [], range: true },
      personnelRange: { type: "create_user", value: [], range: false },
      status: "",
    },
  },
  columns: [],
  proxyConfig: {
    seq: true,
    sort: true,
    filter: true,
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form, sorts }) =>
        new Promise((resolve) => {
          if (sorts.length && sorts[0].order != "null") {
            form.order_key = sorts[0].field;
            form.order_method = sorts[0].order;
          } else {
            form.order_key = "";
            form.order_method = "";
          }

          getNotDesignList({ ...page, ...form }).then((res) => {
            getCount(form);
            resolve({
              data: res.data,
              total: res.total,
            });
          });
        }),
    },
  },
});

const getCount = async (form) => {
  try {
    const res = await notDesignStatistics({
      ...form,
      status: "",
    });
    tabList.value = tabList.value.map((i) => {
      res.data.filter((j) => {
        if (i.name === j.status) {
          i.count = j.count;
        }
      });
      return i;
    });
  } catch (e) {
    throw Error(e);
  }
};

// 查看图片
// 多属性图 2
// 详情图 3
// 橱窗图 1
const checkRoutineImageRef = ref();
const checkImageFun = (row) => {
  if (row.images_url_list.length == 0) {
    ElMessage.error("暂无图片");
    return;
  }
  checkRoutineImageRef?.value.open(row.images_url_list);
};

// 获取自定义字段
const getCustomFieldsList = async (val) => {
  try {
    const res = await getCustomFields({
      apiName: "routine-task",
    });
    CustomFieldsList.value = res.data;
    filterFields();
  } catch (e) {
    throw Error(e);
  }
};

const filterFields = (val) => {
  if (CustomFieldsList.value?.length) {
    const mergedColumns = CustomFieldsList.value
      .filter((column) => column.show === 1) // 仅保留 show 等于 1 的列配置
      .map((customColumnConfig) => {
        const finalColumns = columns.value.find(
          (column) => column.field === customColumnConfig.field
        );
        return finalColumns
          ? { ...finalColumns, ...{ show: customColumnConfig.show } }
          : null;
      })
      .filter((column) => column !== null); // 过滤掉没有匹配的列
    tableOptins.columns = mergedColumns;
    isRefreshTable.value = false;
    nextTick(() => {
      isRefreshTable.value = true;
    });
  } else {
    tableOptins.columns = columns.value;
    isRefreshTable.value = false;
    nextTick(() => {
      isRefreshTable.value = true;
    });
  }
};

onMounted(async () => {
  getCustomFieldsList();
  if (store.picture_spu?.spu) {
    nextTick(() => {
      refAddTask?.value.open("add", store.picture_spu);
      store.createPictureSpu({});
    });
  }

  batchFilterOptions.value = batchRoutineOptions.filter((i) => {
    if ((window.BTN_AUTH || []).includes(i.auth) || !i.auth) {
      return i;
    }
  });
});

const handleCancelTask = (id) => {
  ElMessageBox.confirm(
    "确认取消图片任务？(只允许取消状态为“待分配人员”、“待处理”、“审核未通过”的任务)",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    cancelTask({
      id: [id],
    }).then(() => {
      ElMessage({
        message: "取消任务处理成功",
        type: "success",
      });
    });
    queryForm();
  });
};

const handleBatch = (type, limit) => {
  const recordsData = getSelectRow();
  let falge = null;
  let records = recordsData?.map((row) => row.id);
  if (!records?.length) {
    return ElMessage({
      message: "请先勾选",
      type: "error",
    });
  }
  if (!limit && records.length > limit) {
    return ElMessage({
      message: `只能选择${limit}个上传`,
      type: "error",
    });
  }
  if (type == "designReview") {
    records = [];
    let batchData =
      recordsData.some((item) => item.status === 3) &&
      recordsData.some((item) => item.status === 4);
    if (batchData) {
      return ElMessage({
        message: "只能选择待设计审核数据,不能一起选择!",
        type: "warning",
      });
    }
    let ids3 = recordsData?.filter((item) => item.status == 3)?.map((it) => it.id);
    if (ids3?.length) {
      records = ids3;
      falge = 3;
    }
    if (!records?.length) {
      return ElMessage({
        message: "只能选择待设计审核数据!",
        type: "warning",
      });
    }
  } else if (type == "operationAudit") {
    records = [];
    let batchData =
      recordsData.some((item) => item.status === 3) &&
      recordsData.some((item) => item.status === 4);
    if (batchData) {
      return ElMessage({
        message: "只能选择待运营审核数据,不能一起选择!",
        type: "warning",
      });
    }
    let ids4 = recordsData?.filter((item) => item.status == 4)?.map((it) => it.id);
    if (ids4?.length) {
      records = ids4;
      falge = 4;
    }
    if (!records?.length) {
      return ElMessage({
        message: "只能选择待运营审核数据!",
        type: "warning",
      });
    }
  }
  diaLog.value.open(type, records, falge);
};

const handleCopy = () => {
  if (getSelectRow().length > 1) {
    return ElMessage({
      message: "只能复制一条任务",
      type: "error",
    });
  }
  const records = getSelectRow();

  pictureTaskFun("copy", records[0].task_id);
};

//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords();
};

//更新表格数据
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
const handleClick = (val) => {
  const form = tableRef.value.getForm();
  tableRef.value.setForm({
    ...form,
    status: val.props.name,
  });
  refresh();
};

// 新增/编辑
const pictureTaskFun = (type, id) => {
  nextTick(() => {
    refAddTask?.value.open(type, id);
  });
};

const clearExpandActives = () => {
  expandActives.value.length = 0;
};

const queryForm = () => {
  clearExpandActives();
  nextTick(() => {
    tableRef.value.query();
  });
};

const DerivedCenterRef = ref();
const handleExport = () => {
  const records = getSelectRow().map((i) => {
    return i.images_assignment_task?.task_no;
  });

  const uniqueArray = [...new Set(records)];

  let condition = {};
  if (uniqueArray.length) {
    condition.task_no = uniqueArray;
  } else {
    condition = tableRef.value.getQueryForm();
  }
  DerivedCenterRef.value.open({
    tag_name: "goods_not_design_task",
    condition,
  });
};

const customFieldsRef = ref();
const handleCustom = () => {
  customFieldsRef.value.open(CustomFieldsList.value);
};

const copyData = ref([]);
const copyVisible = ref(false);
const batchOptionsEvent = (val) => {
  const records = getSelectRow();
  if (records.length == 0) {
    return ElMessage({
      message: "至少选择一项",
      type: "error",
    });
  }
  if (val == "extractSku") {
    const skuList = records?.map((i) => i?.goods_sku?.sku);
    const filteredArray = [...new Set(skuList?.filter((item) => item !== ""))];
    const sku = filteredArray.join("\n");
    copyData.value = sku;
    copyVisible.value = true;
    return;
  }
  handleBatch(val, records[0].task_id);
};

const handleKeyUp = (event) => {
  if (event.keyCode === 13 || event.key === "Enter") {
    queryForm();
    event.stopPropagation();
  }
};

// 标签查看
const labelModalRef = ref();
const handlePerformanceLabel = (id) => {
  labelModalRef.value.open("view", { id });
};

const pictureStatisticsRef = ref();
const handleStatistics = (field) => {
  const params = tableRef.value.getQueryForm();
  pictureStatisticsRef.value.open({ type: 2, field, params });
};

// 绩效编辑
const editPerformanceRef = ref();
const handlePerformance = (id) => {
  editPerformanceRef.value.open(id);
};
</script>
<style lang="scss">
@import "./index.scss";
</style>
<style lang="scss" scoped>
.selectClass {
  &:deep(.el-select__wrapper) {
    background-color: var(--base-small-bg-color) !important;
  }
}
</style>
